﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Geodatabase;
using System.IO;

namespace 实习九
{
    public partial class MyMap : Form
    {
        public MyMap()
        {
            ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop);
            InitializeComponent();
        }

        private void AxLicenseControl2_Enter(object sender, EventArgs e)
        {

        }

        private void MyMap_Load(object sender, EventArgs e)
        {

        }

        private void addshpdataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();//好像是创建了一个文件对话框
            openFileDialog.Filter = "shapefile文件(*shp)|*.shp";//添加筛选器，筛选后缀
            DialogResult dialogResult = openFileDialog.ShowDialog();
            if (dialogResult != DialogResult.OK) { return; }  //点击了关闭键而不是确认键
            string path = openFileDialog.FileName;  //文件对话框返回的文件路径
            string folder = System.IO.Path.GetDirectoryName(path);//这句话提取了路径？
            string filename = System.IO.Path.GetFileName(path); //提取文件名

            IWorkspaceFactory workspacefactory = new ShapefileWorkspaceFactory();//实例化了一个工厂类
            IWorkspace workspace = workspacefactory.OpenFromFile(folder, 0);//这句话是啥意思
            if(workspace==null)
            {
                MessageBox.Show("无法打开工作空间");
                return;
            }
            IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;//啥意思
            IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(filename);
            if (featureClass==null)
            {
                MessageBox.Show("无法打开矢量数据集");
                return;
            }
            IFeatureLayer featureLayer = new FeatureLayerClass();

            featureLayer.FeatureClass = featureClass;
            featureLayer.Name = featureClass.AliasName;
            ILayer layer = featureLayer as ILayer;
            axMapControl1.Map.AddLayer(layer);
            axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);



        }
        //矢量要素唯一值渲染
        private void SimpleValueRenderMenuItem_Click(object sender, EventArgs e)
        {
            esriTOCControlItem tocChoosedItem = esriTOCControlItem.esriTOCControlItemLayer;
            IBasicMap basicMap = null;
            ILayer tocChoosedLayer = null;
            object other = new object();
            object index = new object();
            axTOCControl1.GetSelectedItem(
                ref tocChoosedItem,
                ref basicMap,
                ref tocChoosedLayer,
                ref other,
                ref index
            );

            if (tocChoosedLayer is IFeatureLayer)
            {
                FieldSelectDialog fieldSelectDialog = new FieldSelectDialog(tocChoosedLayer as IFeatureLayer);
                DialogResult dialogResult = fieldSelectDialog.ShowDialog();
                if (dialogResult == DialogResult.OK)
                {
                    defineUniqueValueRender(tocChoosedLayer as IFeatureLayer, fieldSelectDialog.selectFieldName());
                }
            }
            else
            {
                MessageBox.Show("未选择图层，或者图层非矢量图层！");
                return;
            }
        }

        private void defineUniqueValueRender(IFeatureLayer featureLayer, string fieldName)
        {
            // 设置颜色列表，用于随机生成颜色（用于填充面状要素）
            // 设置颜色的基本属性，包括色调（H）、饱和度（S）以及亮度（V）
            IRandomColorRamp colorRamp = new RandomColorRamp();
            colorRamp.StartHue = 76;
            colorRamp.EndHue = 188;
            colorRamp.MinSaturation = 20;
            colorRamp.MaxSaturation = 40;
            colorRamp.MinValue = 85;
            colorRamp.MaxValue = 100;

            colorRamp.UseSeed = true;
            colorRamp.Seed = 43;

            // 设置唯一值渲染的相关属性
            IUniqueValueRenderer valueRender = new UniqueValueRenderer();
            valueRender.FieldCount = 1;
            valueRender.set_Field(0, fieldName);

            // 遍历要素类的所有要素，并为每个要素设置基本的渲染样式
            IFeatureClass featureClass = featureLayer.FeatureClass;
            IFeatureCursor featureCursor = featureClass.Search(null, false);
            IFeature feature = featureCursor.NextFeature();

            // 获取指定字段的索引值
            IFields fields = featureCursor.Fields;
            // 存储字段的索引值
            int iFieldIndex = fields.FindField(fieldName);

            // 为不同的要素，设置不同的填充颜色
            colorRamp.Size = featureClass.FeatureCount(null);
            bool bOK;
            // 判断随机颜色生成是否成功
            colorRamp.CreateRamp(out bOK);

            // 获得随机生成的颜色列表
            IEnumColors enumColors = colorRamp.Colors;
            enumColors.Reset();
            IColor color = enumColors.Next();

            // 开始遍历，为每个要素设置基本的渲染信息
            while (feature != null)
            {
                // 为每个要素设置基本的渲染符号
                ISimpleFillSymbol simpleFillFeature = new SimpleFillSymbolClass();
                simpleFillFeature.Style = esriSimpleFillStyle.esriSFSSolid;
                simpleFillFeature.Outline.Width = 0.4;
                simpleFillFeature.Color = color;

                // 获得当前要素中指定字段的名称
                string featureName = Convert.ToString(feature.get_Value(iFieldIndex));

                // 设置唯一值渲染的相关属性
                valueRender.AddValue(featureName, fieldName, simpleFillFeature as ISymbol);
                valueRender.set_Label(featureName, featureName);
                valueRender.set_Symbol(featureName, simpleFillFeature as ISymbol);

                // 获得下一组要素和颜色
                feature = featureCursor.NextFeature();
                color = enumColors.Next();
            }

            // 接口转换，对渲染方式进行设置
            IGeoFeatureLayer geoFeatureLayer = featureLayer as IGeoFeatureLayer;
            geoFeatureLayer.Renderer = valueRender as IFeatureRenderer;

            // 地图刷新
            axMapControl1.Refresh();
        }

        //矢量要素简单渲染事件处理函数
        private void simple_renderingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            esriTOCControlItem tocChoosedItem = esriTOCControlItem.esriTOCControlItemLayer;//非常诡异的实例化方式
            IBasicMap basicMap = null;
            ILayer tocChoosedLayer = null;
            object other = new object();
            object index = new object();
            axTOCControl1.GetSelectedItem(
                ref tocChoosedItem,
                ref basicMap,
                ref tocChoosedLayer,
                ref other,
                ref index);

            if(tocChoosedLayer is IFeatureLayer)
            {
                defineSimpleRender(tocChoosedLayer as IFeatureLayer);
            }
            else
            {
                MessageBox.Show("未选择图层，或非矢量图层");
                return;
            }

        }
    private void defineSimpleRender(IFeatureLayer featureLayer)
        {
            IRgbColor color = new RgbColor();
            color.Red = 255;
            color.Blue = 0;
            color.Green = 0;

            ISimpleFillSymbol simpleFillSymbol = new SimpleFillSymbol();
            simpleFillSymbol.Style = esriSimpleFillStyle.esriSFSSolid;
            simpleFillSymbol.Outline.Width = 0.4;
            simpleFillSymbol.Color = color as IColor;

            ISimpleRenderer simpleRenderer = new SimpleRendererClass();
            simpleRenderer.Symbol = simpleFillSymbol as ISymbol;

            IGeoFeatureLayer geoFeatureLayer = featureLayer as IGeoFeatureLayer;
            geoFeatureLayer.Renderer = simpleRenderer as IFeatureRenderer;

            axMapControl1.Refresh();

        }
        //查看属性事件处理函数
        private void attributesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            esriTOCControlItem tocChoosedItem = esriTOCControlItem.esriTOCControlItemLayer;//获得当前选中图层参数
            IBasicMap basicMap = null;
            ILayer tocChoosedLayer = null;
            object other = new object();
            object index = new object();
            axTOCControl1.GetSelectedItem(
                ref tocChoosedItem,
                ref basicMap,
                ref tocChoosedLayer,
                ref other,
                ref index);
            if (tocChoosedLayer is IFeatureLayer)
            {
        
                FeatureAttributeTable shuxingform = new FeatureAttributeTable(tocChoosedLayer as IFeatureLayer);//传参数形成窗口
                DialogResult dialogResult = shuxingform.ShowDialog();//为窗体进行显示
            }
            else
            {
                MessageBox.Show("未选择要素层，或选择非矢量层");
            }
        }

        private void NewMxdDocMenuItem_Click(object sender, EventArgs e)
        {
            MyMxdDoc myMapDoc = new MyMxdDoc() ;//仅在调用改方法时创建类实例
            myMapDoc.newMapDoc(axMapControl1);
        }

        private void OpenMxdItem_Click(object sender, EventArgs e)
        {
            MyMxdDoc myMapDoc = new MyMxdDoc();//仅在调用改方法时创建类实例
            myMapDoc.openMapDoc(axMapControl1);
        }

        private void SaveMxdDocItem_Click(object sender, EventArgs e)
        {
            MyMxdDoc myMapDoc = new MyMxdDoc();//仅在调用改方法时创建类实例
            myMapDoc.saveMapDoc(axMapControl1);
        }

        private void OthersaveMxdDocItem_Click(object sender, EventArgs e)
        {
            MyMxdDoc myMapDoc = new MyMxdDoc();//仅在调用改方法时创建类实例
            myMapDoc.SaveAsMapDoc(axMapControl1);
        }
    }

}
